<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>竞赛详情 - {{ competitionInfo.name }}</span>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">保存设置</el-button>
        </div>
      </template>
      
      <!-- 竞赛基本信息 -->
      <el-descriptions :column="2" border>
        <el-descriptions-item label="竞赛名称">{{ competitionInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="竞赛组别">
          <el-tag v-if="competitionInfo.groupType===1">本科组</el-tag>
          <el-tag type="warning" v-else-if="competitionInfo.groupType===2">专科组</el-tag>
          <el-tag type="success" v-else>研究生组</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ competitionInfo.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ competitionInfo.endTime }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ competitionInfo.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 主办高校设置 -->
      <el-col :span="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>主办高校设置</span>
              <el-button type="primary" size="small" @click="handleAddUniversity">添加高校</el-button>
            </div>
          </template>
          
          <el-table :data="universityList" style="width: 100%">
            <el-table-column prop="name" label="高校名称" />
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button link type="danger" @click="handleRemoveUniversity(scope.$index)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 赛制设置 -->
      <el-col :span="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>赛制设置</span>
            </div>
          </template>
          
          <el-form :model="rulesForm" label-width="100px">
            <el-form-item label="选择赛制">
              <el-select v-model="rulesForm.rulesId" placeholder="请选择赛制" clearable style="width: 100%;">
                <el-option
                  v-for="rule in rulesOptions"
                  :key="rule.id"
                  :label="`${rule.matchType} (${rule.competitionType === 1 ? '团队赛' : '个人赛'})`"
                  :value="rule.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="selectedRule" label="最大人数">
              <el-input v-model="selectedRule.maxParticipants" disabled />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 奖项设置 -->
      <el-col :span="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>奖项设置</span>
            </div>
          </template>
          
          <el-form :model="awardForm" label-width="100px">
            <el-form-item label="一等奖">
              <el-select v-model="awardForm.firstPrize" placeholder="请选择一等奖奖品" clearable style="width: 100%;">
                <el-option
                  v-for="prize in prizeOptions"
                  :key="prize.id"
                  :label="prize.name"
                  :value="prize.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="二等奖">
              <el-select v-model="awardForm.secondPrize" placeholder="请选择二等奖奖品" clearable style="width: 100%;">
                <el-option
                  v-for="prize in prizeOptions"
                  :key="prize.id"
                  :label="prize.name"
                  :value="prize.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="三等奖">
              <el-select v-model="awardForm.thirdPrize" placeholder="请选择三等奖奖品" clearable style="width: 100%;">
                <el-option
                  v-for="prize in prizeOptions"
                  :key="prize.id"
                  :label="prize.name"
                  :value="prize.id"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 竞赛试题管理 -->
    <el-card class="box-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>竞赛试题管理</span>
          <el-button type="primary" @click="handleUploadTopic" :loading="uploadLoading">上传试题</el-button>
        </div>
      </template>
      
      <el-table :data="topicList" style="width: 100%">
        <el-table-column prop="fileName" label="文件名" />
        <el-table-column prop="fileSize" label="文件大小">
          <template #default="scope">
            {{ formatFileSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column prop="fileType" label="文件类型" />
        <el-table-column prop="createTime" label="上传时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button link type="primary" @click="handlePreviewTopic(scope.row)">预览</el-button>
            <el-button link type="success" @click="handleDownloadTopic(scope.row)">下载</el-button>
            <el-button link type="danger" @click="handleDeleteTopic(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加高校对话框 -->
    <el-dialog title="添加主办高校" v-model="universityDialogVisible" width="500px" append-to-body>
      <el-form :model="universityForm" label-width="100px">
        <el-form-item label="选择高校">
          <el-select v-model="universityForm.universityId" placeholder="请选择高校" style="width: 100%;">
            <el-option
              v-for="university in availableUniversities"
              :key="university.id"
              :label="university.name"
              :value="university.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleConfirmAddUniversity">确 定</el-button>
          <el-button @click="universityDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 试题上传对话框 -->
    <el-dialog title="上传竞赛试题" v-model="topicDialogVisible" width="500px" append-to-body>
      <el-upload
        ref="uploadRef"
        v-model:file-list="fileList"
        :auto-upload="false"
        :on-change="handleFileChange"
        :before-upload="beforeUpload"
        accept=".pdf,.docx,.doc"
        drag
        multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传PDF、DOCX、DOC格式的文件，且不超过10MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleConfirmUpload" :loading="uploadLoading">确 定</el-button>
          <el-button @click="topicDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog title="文件预览" v-model="previewDialogVisible" width="80%" append-to-body>
      <div v-if="previewFile" style="height: 600px;">
        <div v-if="previewLoading" style="text-align: center; padding: 50px;">
          <el-icon class="is-loading" size="32"><Loading /></el-icon>
          <p style="margin-top: 20px;">正在加载预览...</p>
        </div>
        <iframe 
          v-else-if="previewFile.fileType === 'pdf' && previewUrl"
          :src="previewUrl" 
          style="width: 100%; height: 100%; border: none;"
          @load="handlePreviewLoad"
          @error="handlePreviewError"
        ></iframe>
        <div v-else style="text-align: center; padding: 50px;">
          <el-icon size="64" color="#409EFF"><Document /></el-icon>
          <p style="margin-top: 20px;">该文件类型不支持在线预览，请下载后查看</p>
          <el-button type="primary" @click="handleDownloadTopic(previewFile)">下载文件</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { UploadFilled, Document, Loading } from '@element-plus/icons-vue'
import { getCompetition } from '@/api/race/competition'
import { listUniversity } from '@/api/race/university'
import { listPrize } from '@/api/race/prize'
import { getAllCompetitionRules } from '@/api/race/competitionRules'
import { getCompetitionDetailByCompetitionId, addCompetitionDetail, updateCompetitionDetail } from '@/api/race/competitionDetail'
import { listCompetitionTopicByCompetition, uploadCompetitionTopic, delCompetitionTopic, getPresignedUrl } from '@/api/race/competitionTopic'

const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()

const competitionInfo = ref({})
const universityList = ref([])
const prizeOptions = ref([])
const rulesOptions = ref([])
const availableUniversities = ref([])
const saveLoading = ref(false)
const universityDialogVisible = ref(false)

// 试题相关
const topicList = ref([])
const topicDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const uploadLoading = ref(false)
const fileList = ref([])
const previewFile = ref(null)
const uploadRef = ref()
const previewLoading = ref(false)
const previewUrl = ref('')

const awardForm = reactive({
  firstPrize: null,
  secondPrize: null,
  thirdPrize: null
})

const rulesForm = reactive({
  rulesId: null
})

const universityForm = reactive({
  universityId: null
})

// 计算属性：选中的赛制
const selectedRule = computed(() => {
  if (!rulesForm.rulesId) return null
  return rulesOptions.value.find(rule => rule.id === rulesForm.rulesId)
})

// 获取竞赛详情
async function getCompetitionDetail() {
  try {
    const competitionId = route.params.id
    const response = await getCompetition(competitionId)
    competitionInfo.value = response.data
  } catch (error) {
    console.error('获取竞赛详情失败:', error)
    proxy.$modal.msgError('获取竞赛详情失败')
  }
}

// 获取奖品列表
async function loadPrizeOptions() {
  try {
    const response = await listPrize({ pageNum: 1, pageSize: 1000 })
    prizeOptions.value = response.rows
  } catch (error) {
    console.error('获取奖品列表失败:', error)
  }
}

// 获取赛制列表
async function loadRulesOptions() {
  try {
    const response = await getAllCompetitionRules()
    rulesOptions.value = response.data
  } catch (error) {
    console.error('获取赛制列表失败:', error)
  }
}

// 获取可用高校列表
async function loadAvailableUniversities() {
  try {
    const response = await listUniversity({ pageNum: 1, pageSize: 1000 })
    availableUniversities.value = response.rows.map(university => ({
      ...university,
      regionName: university.regionName || '未知地区'
    }))
  } catch (error) {
    console.error('获取高校列表失败:', error)
  }
}

// 添加高校
function handleAddUniversity() {
  universityForm.universityId = null
  universityDialogVisible.value = true
}

// 确认添加高校
function handleConfirmAddUniversity() {
  if (!universityForm.universityId) {
    proxy.$modal.msgWarning('请选择高校')
    return
  }
  
  const selectedUniversity = availableUniversities.value.find(u => u.id === universityForm.universityId)
  if (selectedUniversity) {
    // 检查是否已经添加过
    const exists = universityList.value.some(u => u.id === selectedUniversity.id)
    if (exists) {
      proxy.$modal.msgWarning('该高校已经添加过了')
      return
    }
    
    universityList.value.push({
      id: selectedUniversity.id,
      name: selectedUniversity.name
    })
    universityDialogVisible.value = false
  }
}

// 移除高校
function handleRemoveUniversity(index) {
  universityList.value.splice(index, 1)
}

// 保存设置
async function handleSave() {
  saveLoading.value = true
  try {
    const competitionId = competitionInfo.value.id
    
    // 构建保存数据
    const detailData = {
      competitionId: competitionId,
      universityId: universityList.value.length > 0 ? universityList.value[0].id : null, // 取第一个高校作为主办高校
      rulesId: rulesForm.rulesId,
      firstPrizeId: awardForm.firstPrize,
      secondPrizeId: awardForm.secondPrize,
      thirdPrizeId: awardForm.thirdPrize
    }
    
    // 检查是否已存在详情记录
    const existingDetail = await getCompetitionDetailByCompetitionId(competitionId)
    
    if (existingDetail.data) {
      // 更新现有记录
      detailData.id = existingDetail.data.id
      await updateCompetitionDetail(detailData)
    } else {
      // 创建新记录
      await addCompetitionDetail(detailData)
    }
    
    proxy.$modal.msgSuccess('设置保存成功')
    
    // 保存成功后关闭页面，返回竞赛管理页面
    setTimeout(() => {
      router.push('/race/competition')
    }, 1000)
  } catch (error) {
    console.error('保存设置失败:', error)
    proxy.$modal.msgError('保存设置失败')
  } finally {
    saveLoading.value = false
  }
}

// 加载现有详情数据
async function loadExistingDetail() {
  try {
    const competitionId = competitionInfo.value.id
    const response = await getCompetitionDetailByCompetitionId(competitionId)
    if (response.data) {
      const detail = response.data
      
      // 设置奖项
      awardForm.firstPrize = detail.firstPrizeId
      awardForm.secondPrize = detail.secondPrizeId
      awardForm.thirdPrize = detail.thirdPrizeId
      
      // 设置赛制
      rulesForm.rulesId = detail.rulesId
      
      // 设置主办高校
      if (detail.universityId) {
        const university = availableUniversities.value.find(u => u.id === detail.universityId)
        if (university) {
          universityList.value = [{
            id: university.id,
            name: university.name
          }]
        }
      }
    }
  } catch (error) {
    console.error('加载现有详情失败:', error)
  }
}

// 加载试题列表
async function loadTopicList() {
  try {
    const competitionId = competitionInfo.value.id
    const response = await listCompetitionTopicByCompetition(competitionId)
    topicList.value = response.data || []
  } catch (error) {
    console.error('加载试题列表失败:', error)
  }
}

// 上传试题
function handleUploadTopic() {
  fileList.value = []
  topicDialogVisible.value = true
}

// 文件选择处理
function handleFileChange(file, fileListParam) {
  // 检查文件类型
  const allowedTypes = ['pdf', 'docx', 'doc']
  const fileType = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
  if (!allowedTypes.includes(fileType)) {
    proxy.$modal.msgError('只支持上传PDF、DOCX、DOC格式的文件')
    return false
  }
  
  // 检查文件大小 (10MB)
  if (file.size > 10 * 1024 * 1024) {
    proxy.$modal.msgError('文件大小不能超过10MB')
    return false
  }
  
  return true
}

// 上传前检查
function beforeUpload(file) {
  const allowedTypes = ['pdf', 'docx', 'doc']
  const fileType = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
  if (!allowedTypes.includes(fileType)) {
    proxy.$modal.msgError('只支持上传PDF、DOCX、DOC格式的文件')
    return false
  }
  
  if (file.size > 10 * 1024 * 1024) {
    proxy.$modal.msgError('文件大小不能超过10MB')
    return false
  }
  
  return true
}

// 确认上传
async function handleConfirmUpload() {
  if (fileList.value.length === 0) {
    proxy.$modal.msgWarning('请选择要上传的文件')
    return
  }
  
  uploadLoading.value = true
  try {
    const competitionId = competitionInfo.value.id
    
    for (const file of fileList.value) {
      // 确保使用正确的文件对象
      const fileToUpload = file.raw || file
      await uploadCompetitionTopic(fileToUpload, competitionId)
    }
    
    proxy.$modal.msgSuccess('上传成功')
    topicDialogVisible.value = false
    fileList.value = [] // 清空文件列表
    await loadTopicList()
  } catch (error) {
    console.error('上传失败:', error)
    proxy.$modal.msgError('上传失败')
  } finally {
    uploadLoading.value = false
  }
}

// 预览试题
async function handlePreviewTopic(topic) {
  previewFile.value = topic
  previewDialogVisible.value = true
  previewLoading.value = true
  previewUrl.value = ''
  
  try {
    // 从URL中提取bucket和object信息
    // URL格式通常是: http://localhost:9000/bucket-name/object-name
    const url = topic.url
    const urlParts = url.split('/')
    if (urlParts.length >= 4) {
      const bucket = urlParts[3] // bucket名称
      const object = urlParts.slice(4).join('/') // object路径
      
      // 获取预签名URL
      const response = await getPresignedUrl(bucket, object, 3600)
      previewUrl.value = response.data
    } else {
      // 如果无法解析URL，直接使用原URL
      previewUrl.value = url
    }
  } catch (error) {
    console.error('获取预签名URL失败:', error)
    // 如果获取预签名URL失败，尝试直接使用原URL
    previewUrl.value = topic.url
  } finally {
    previewLoading.value = false
  }
}

// 预览加载完成
function handlePreviewLoad() {
  previewLoading.value = false
}

// 预览加载错误
function handlePreviewError() {
  previewLoading.value = false
  proxy.$modal.msgError('文件预览失败，请尝试下载文件')
}

// 下载试题
function handleDownloadTopic(topic) {
  const link = document.createElement('a')
  link.href = topic.url
  link.download = topic.fileName
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 删除试题
async function handleDeleteTopic(topic) {
  try {
    await proxy.$modal.confirm('确定要删除该试题吗？')
    await delCompetitionTopic([topic.id])
    proxy.$modal.msgSuccess('删除成功')
    await loadTopicList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      proxy.$modal.msgError('删除失败')
    }
  }
}

// 格式化文件大小
function formatFileSize(size) {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024
    index++
  }
  return `${size.toFixed(2)} ${units[index]}`
}

onMounted(async () => {
  await getCompetitionDetail()
  await loadPrizeOptions()
  await loadRulesOptions()
  await loadAvailableUniversities()
  await loadExistingDetail()
  await loadTopicList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
